package common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class SessionDemo
{
	private static String convertStreamToString(InputStream inputStream) throws IOException
	{
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		StringBuffer sb = new StringBuffer();
		String Line = null;
		try
		{
			while ((Line = reader.readLine()) != null)
			{
				sb.append(Line);
			}
		}
		catch (IOException e)
		{
			// 转换失败，返回null
			reader.close();
			return null;
		}

		reader.close();
		// String ret = new String(sb.toString().getBytes("GBK"), "UTF-8");
		String ret = sb.toString();
		return ret;
	}

	public static String getCookie() throws IOException
	{
		URL url = new URL("http://172.3.207.26/Go/?url=/Html/PersonalCenter/healthArchive.htmle");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestProperty("token", "ph/U6MvP0iqwsdYaWJQvKA==");

		connection.setInstanceFollowRedirects(false);

		connection.setConnectTimeout(30 * 1000);
		connection.setReadTimeout(30 * 1000);

		connection.getInputStream();
		String cookie = connection.getHeaderField("Set-Cookie");
		connection.disconnect();
		return cookie;
	}

	public static void openUrl(String cookie) throws IOException
	{
		URL url = new URL("http://172.3.207.26/api/UserCase");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestProperty("Cookie", cookie);

		connection.setConnectTimeout(30 * 1000);
		connection.setReadTimeout(30 * 1000);

		String result;
		try
		{
			result = convertStreamToString(connection.getInputStream());
			System.out.println(result);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		// 关闭HTTP连接
		connection.disconnect();
	}

	public static void main(String[] args) throws IOException
	{
		String cookie = getCookie();

		openUrl(cookie);

	}

}
